package com.kly.user.utils;

import com.kly.user.constant.ConstantType;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class UserSnowflake {

    private static final long TWEPOCH = 1288834974657L;
    private static final long DATACENTER_ID_BITS = 2L;
    private static final long WORKER_ID_BITS = 8L;
    private static final long MAX_DATACENTER_ID = -1L ^ (-1L << DATACENTER_ID_BITS);
    private static final long MAX_WORKER_ID = -1L ^ (-1L << WORKER_ID_BITS);
    private static final long SEQUENCE_BITS = 12L;

    private static final long WORKER_ID_SHIFT = SEQUENCE_BITS;
    private static final long DATACENTER_ID_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS;
    private static final long TIMESTAMP_LEFT_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS + DATACENTER_ID_BITS;
    private static final long SEQUENCE_MASK = -1L ^ (-1L << SEQUENCE_BITS);

    private long workerId;
    private long datacenterId;
    private long sequence = 0L;
    private long lastTimestamp = -1L;

    private UserSnowflake(long workerId, long datacenterId) {
        if (workerId > MAX_WORKER_ID || workerId < 0) {
            throw new IllegalArgumentException(
                    String.format("worker Id can't be greater than %d or less than 0", MAX_WORKER_ID));
        }
        if (datacenterId > MAX_DATACENTER_ID || datacenterId < 0) {
            throw new IllegalArgumentException(
                    String.format("datacenter Id can't be greater than %d or less than 0", MAX_DATACENTER_ID));
        }
        this.workerId = workerId;
        this.datacenterId = datacenterId;
    }

    public synchronized long nextId() {
        long timestamp = timeGen();

        if (timestamp < lastTimestamp) {
            throw new RuntimeException(
                    String.format("Clock moved backwards.  Refusing to generate id for %d milliseconds",
                            lastTimestamp - timestamp));
        }

        if (lastTimestamp == timestamp) {
            sequence = (sequence + 1) & SEQUENCE_MASK;
            if (sequence == 0) {
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            sequence = 0L;
        }

        lastTimestamp = timestamp;

        return ((timestamp - TWEPOCH) << TIMESTAMP_LEFT_SHIFT) | (datacenterId << DATACENTER_ID_SHIFT)
                | (workerId << WORKER_ID_SHIFT) | sequence;
    }

    private long tilNextMillis(long lastTimestamp) {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = timeGen();
        }
        return timestamp;
    }

    private long timeGen() {
        return System.currentTimeMillis();
    }


    /**
     * @return  workerId
     */
    private static int generateWorkerId() {
        InetAddress address;
        try {
            // 获取本地IP地址
            address = InetAddress.getLocalHost();
            // 提取IP地址的最后一段作为workerId
            byte[] ipAddressByteArray = address.getAddress();
            return (ipAddressByteArray[ipAddressByteArray.length - 1] & 0xFF) % 256;
        } catch (UnknownHostException e) {
            throw new RuntimeException("Unable to get local host address.", e);
        }

    }


    private static volatile UserSnowflake instance;

    public static UserSnowflake getInstance() {
        if (instance == null) {  // 第一次检查
            synchronized (UserSnowflake.class) {  // 获取Singleton类的锁
                if (instance == null) {  // 第二次检查
                    instance = new UserSnowflake(generateWorkerId(), ConstantType.DATACENTER_ID);  // 创建新的Singleton实例
                }
            }
        }
        return instance;
    }

}
